﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Diary.Win
{
    public partial class ContentManagerForm : Form
    {
        public ContentManagerForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 用于窗体间数据传递
        /// </summary>
        public Model.Content ContentData = new Model.Content();

        private void btnOK_Click(object sender, EventArgs e)
        {
            SaveData();
        }

        string encode(string content)
        {
            //base64
            //try
            //{
            //    byte[] bytedata = System.Text.Encoding.ASCII.GetBytes(content);
            //    return Convert.ToBase64String(bytedata, 0, bytedata.Length);
            //}
            //catch (Exception ex)
            //{
            //    return "";
            //}
            return System.Web.HttpUtility.UrlEncode(content);
        }

        string decode(string content)
        {
            //base64
            //try
            //{
            //    byte[] outputb = Convert.FromBase64String(content);
            //    return System.Text.Encoding.ASCII.GetString(outputb);
            //}
            //catch (Exception ex)
            //{
            //    return "";
            //}

            return System.Web.HttpUtility.UrlDecode(content);
        }

        void SaveData()
        {
            if (ContentData.Id == 0)
            {
                ContentData.CreateTime = System.DateTime.Now;
            }

            ContentData.Title = tbxTitle.Text;
            ContentData.SubTitle = tbxSubTitle.Text;
            ContentData.CategoryId = (int)cbxCategory.SelectedValue;
            ContentData.Type = cbxType.SelectedValue.ToString();
            ContentData.RealTime = dtpRealDate.Value;
            ContentData.MainBody = encode(tbxMainBody.Rtf);
            ContentData.Summary = tbxSummary.Text;
            ContentData.Description = tbxDescription.Text;
            ContentData.Remark = tbxRemark.Text;
            ContentData.ModifyTime = DateTime.Now;

            bool isOK = false;
            if (ContentData.Id > 0)
            {
                isOK = BAL.Content.Modify(ContentData);
            }
            else
            {
                ContentData = BAL.Content.Insert(ContentData);
                isOK = ContentData != null;
            }

            lblTip.Text = string.Format("{0} - {1}", isOK ? "保存成功": "保存失败", System.DateTime.Now.ToString("HH:mm:ss"));
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void CategoryManagerForm_Load(object sender, EventArgs e)
        {
            //所属分类
            List<Model.Category> listCategory = BAL.Category.query_all();
            listCategory.Add(new Model.Category { Id = -1, Name = "无", HasChild = false, ParentId = -1, Type = "Normal", ShowOrder = 0 });
            cbxCategory.DataSource = Model.Category.Sort(listCategory);
            cbxCategory.DisplayMember = "Name";
            cbxCategory.ValueMember = "Id";

            //分类类型
            List<Tuple<string, string>> listType = new List<Tuple<string, string>>()
            {
                new Tuple<string, string>("正常", "Normal"),
                new Tuple<string, string>("代码", "Code"),
            };
            
            cbxType.DataSource = listType;
            cbxType.DisplayMember = "Item1";
            cbxType.ValueMember = "Item2";

            //初始化控件
            if (ContentData.Id > 0)
            {
                //修改
                Text = string.Format("{0}(ID:{1})", Text, ContentData.Id);
                tbxTitle.Text = ContentData.Title;
                tbxSubTitle.Text = ContentData.SubTitle;
                try
                {
                    tbxMainBody.Rtf = decode(ContentData.MainBody);
                }
                catch (Exception ex)
                {
                    tbxMainBody.Text = ContentData.MainBody;
                }
                cbxCategory.SelectedValue = ContentData.CategoryId;
                cbxType.SelectedValue = ContentData.Type;
                dtpRealDate.Value = ContentData.RealTime;
                tbxSummary.Text = ContentData.Summary;
                tbxDescription.Text = ContentData.Description;
                tbxRemark.Text = ContentData.Remark;
            }
            else
            {
                //新建
                Text = string.Format("{0}(新建)", Text);
                //tbxShowOrder.Text = "99";
                if (ContentData != null)
                {
                    cbxCategory.SelectedValue = ContentData.CategoryId;
                }
                cbxType.SelectedValue = "Normal";
            }
        }

        private void cbxParent_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0) return;

            e.DrawBackground();
            e.DrawFocusRectangle();

            Brush brush = new SolidBrush(e.ForeColor);
            Model.Category category = cbxCategory.Items[e.Index] as Model.Category;
            if (category == null) return;

            string text = "";
            for (int i = 1; i <= category.Depth; i++)
            {
                text += "    ";
            }
            text += category.Name;

            Font font = null;
            if (category.HasChild)
            {
                font = new Font(e.Font.FontFamily, e.Font.Size, FontStyle.Bold);
            }
            else
            {
                font = new Font(e.Font.FontFamily, e.Font.Size);
            }

            e.Graphics.DrawString(text, font, brush, e.Bounds.X, e.Bounds.Y + 3);
            brush.Dispose();
            font.Dispose();
        }

        private void btnCopyAsHtml_Click(object sender, EventArgs e)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            string html = RtfPipe.Rtf.ToHtml(tbxMainBody.Rtf);
            ClipboardHelper.CopyToClipboard(html, "");
        }

        private void ContentManagerForm_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.S:
                    { 
                        if (e.Control)
                        {
                            SaveData();
                        }
                    }
                    break;
            }
        }

        private void tbxMainBody_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.V:
                    {
                        if (e.Control)
                        {
                            var s = Clipboard.GetData(DataFormats.Html);
                        }

                    }
                    break;
            }
            
        }

        private void tsbBold_Click(object sender, EventArgs e)
        {
            if (tbxMainBody.SelectionFont == null) return;
            Font selFont = tbxMainBody.SelectionFont;
            Font font = new Font(selFont.FontFamily, selFont.Size, selFont.Style == FontStyle.Bold ? FontStyle.Regular : FontStyle.Bold);
            tbxMainBody.SelectionFont = font;
            selFont.Dispose();
        }

        private void tsbFont_Click(object sender, EventArgs e)
        {


        }

        private void tsbFontSize_Click(object sender, EventArgs e)
        {
            if (tbxMainBody.SelectionFont == null) return;
            Font selFont = tbxMainBody.SelectionFont;
            FontDialog dlg = new FontDialog();
            dlg.Font = selFont;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                tbxMainBody.SelectionFont = dlg.Font;
                selFont.Dispose();
            }
        }

        private void tsbFontColor_Click(object sender, EventArgs e)
        {
            if (tbxMainBody.SelectionFont == null) return;
            ColorDialog dlg = new ColorDialog();
            dlg.AnyColor = true;
            dlg.FullOpen = true;
            dlg.Color = tbxMainBody.SelectionColor;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                tbxMainBody.SelectionColor = dlg.Color;
            }
        }
    }

}
